package com.zrq.jwtdemo.core.exception;

import com.zrq.jwtdemo.core.constant.Constant;
import com.zrq.jwtdemo.core.result.APIResponse;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author:
 * @CreateDate: 2020/12/3
 * @Version: 类说明：异常拦截器
 */
@RestControllerAdvice
public class ApiExceptionConfig{

    @ExceptionHandler(AppException.class)
    public APIResponse getExceptionHandler(AppException e) {
        return APIResponse.builder()
                .code(e.getCode())
                .date(e.getMessages())
                .build();
    }

    /**
     * 校验返回错吴
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public APIResponse getExceptionHandler(MethodArgumentNotValidException e) {
        MethodArgumentNotValidException es = e;
        BindingResult result = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder() ;
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                errorMsg.append(error.getDefaultMessage()).append("!");
            });
        }
        return APIResponse.builder()
                .code(Constant.ERROR_CODE)
                .date(errorMsg)
                .build();
    }

    @ExceptionHandler(SignatureException.class)
    public APIResponse getSignatureException(SignatureException e) {
        return APIResponse.builder()
                .code(Constant.ERROR_CODE)
                .date("密钥不正确")
                .build();
    }

    @ExceptionHandler(MalformedJwtException.class)
    public APIResponse getSignatureException(MalformedJwtException e) {
        return APIResponse.builder()
                .code(Constant.ERROR_CODE)
                .date("token过期")
                .build();
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public APIResponse getExpiredJwtException(ExpiredJwtException e) {
        return APIResponse.builder()
                .code(Constant.ERROR_CODE)
                .date("token过期")
                .build();
    }





}
